<!--
* description: 旧件管理-门店返件登记
* author: wangjuan
* createdDate: 2021-3-8
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
    />

    <detail
      :key="detailPopupsKey"
      :dynamic-edit-row-data="detailRowData"
      :popups-visible.sync="detailPopupsVisible"
      :popups-state="editPopupsState"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />
    <print-table
      :key="printPopupsKey"
      :popups-visible.sync="printPopupsVisible"
      :data-for-form="printRowData"
      @closePrint="closePrint"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import Vue from "vue";
import api from "@/api/se/coreManagement";
import printTable from "./printTable";

export default {
  name: "StoreReturnRegistration",

  components: {
    OneTableTemplate,
    printTable,
    Edit: () => import("./edit"),
    Detail: () => import("./detail"),
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function () {
      next();
    });
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      editRowData: {},
      editPopupsVisible: false,

      printPopupsVisible: false,
      printPopupsKey: "1",
      printRowData: [],

      detailPopupsKey: "1",
      detailRowData: {},
      detailPopupsVisible: false,
      // 网格查询API配置对象
      apiConfig: api.rtuRegistration,

      refreshTableKey: "0",

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          name: "search",
          clickEvent: () => this.queryTable(1),
          text: this.$t("sys.button.query"),
          position: "right",
          fuzzySearch: true,
        },
        {
          compKey: "btnKey2",
          size: "small",
          name: "add",
          clickEvent: this.add,
          text: this.$t("sys.button.add"),
          position: "left",
        },
        {
          compKey: "btnKey3",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: this.$t("sys.button.reset"),
          position: "right",
        },
        {
          compKey: "btnKey3",
          size: "small",
          text: "旧件卡打印",
          position: "left",
          clickEvent: () => this.allow(),
        },
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              {
                compKey: "compKey1",
                labelName: "返件单号：",
                codeField: "returnCode",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey2",
                labelName: "返件类型：",
                codeField: "returnType",
                component: () => import("@/components/org/LookupValue"),
                oFields: "returnType,returnTypeName",
                options: [
                  { returnType: "0", returnTypeName: "普通" },
                  { returnType: "1", returnTypeName: "快返" },
                ],
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey3",
                labelName: "返件状态：",
                codeField: "returnStatus",
                component: () => import("@/components/org/LookupValue"),
                oFields: "returnStatus,returnStatusName",
                options: [
                  { returnStatus: "0", returnStatusName: "已登记" },
                  { returnStatus: "1", returnStatusName: "已发运" },
                  { returnStatus: "2", returnStatusName: "已收货" },
                ],
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "返件日期：",
                codeField: "realDateStart,realDateEnd",
                component: () =>
                  import("@/components/org/datePicker/twoDatePicker"),
                type: "twoDatePicker",
                rmat: "yyyy-MM-dd HH:mm:ss",
                isMul: false,
                isMust: true,
              },
            ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "releaseId",
                label: "主键ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "controlBtn1",
                label: "操作",
                width: 150,
                isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "编辑",
                    rowFileds: "show:returnStatusName-已登记",
                    component: () => import("@/components/org/linkButton"),
                    clickEvent: (index) => this.edit(index),
                  },
                  {
                    compKey: "propKey2",
                    labelName: "详情",
                    component: () => import("@/components/org/linkButton"),
                    clickEvent: (index) => {
                      this.detail(index);
                    },
                  },
                ],
              },
              {
                prop: "returnCode",
                label: "返件单号",
                width: 140,
              },
              {
                prop: "returnTypeName",
                label: "返件类型",
              },
              {
                prop: "returnStatusName",
                label: "返件状态",
              },
              {
                prop: "realDate",
                label: "返件时间",
                width: 140,
              },
              {
                prop: "userName",
                label: "记录人",
              },
              {
                prop: "recordDate",
                label: "记录时间",
                width: 140,
              },
              {
                prop: "remark",
                label: "备注",
                width: 140,
              },
            ],

      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          returnCode: "",
          returnType: "",
          returnStatus: "",
          realDateStart: "",
          realDateEnd: "",
          updateControlId: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectTable = selection;
        },
      },
    };
  },

  mounted() {
    // 列表查询
    this.queryTable(1);
  },

  methods: {
    // 编辑
    edit(index) {
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.rtuRegistrationInfor,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          returnCode: this.$refs["multipleTable"].list[index].returnCode,
        },
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.editRowData = Object.assign(
            {},
            response.rows[0],
            this.$refs["multipleTable"].list[index]
          );
          this.editPopupsState = "edit";
          this.editPopupsVisible = true;
        }
      });
    },

    //关闭旧件打印标签
    closePrint() {
      this.printPopupsVisible = false;
      this.printPopupsKey = this.$utils.generateId();
    },

    //旧件卡打印
    allow() {
      // preAuthorCode=this.preAuthorCode
      let arr = [];
      this.selectTable.forEach(function (el) {
        arr.push(el.preAuthorCode);
      });

      let AuthorCodestr = arr.toString();
      // console.log("9999999999", AuthorCodestr);

      // console.log("222222222", this.selectTable);

      if (this.selectTable.length === 0) {
        this.$message({
          message: "无选中数据",
          type: "warn",
          duration: 2000,
        });
        return;
      }

      this.printPopupsVisible = true;
      this.printPopupsKey = this.$utils.generateId();
      // if (this.selectTable.length > 1) {
      //   this.$message({
      //     message: '交车单只能单次打印',
      //     duration: 2000
      //   })
      // } else {
      //   this.printRowData = this.selectTable[0]
      //   this.printPopupsVisible = true
      //   this.printPopupsKey = this.$utils.generateId()
      // }
      this.$requestAPI({
        apiUrl: api.printCoreInfor.APIUrl,
        variables: {
          preAuthorCode: AuthorCodestr,
        },
      }).then((res) => {
        // console.log("8888888888", res);
        if (res.result === "1") {
          // this.printRowData = res.rows;

          this.printRowData = res.rows;
          // console.log("666666666", this.printRowData);
        }
      });
    },

    add() {
      this.editPopupsState = "add";
      this.editPopupsVisible = true;
    },

    detail(index) {
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.rtuRegistrationInfor,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          returnCode: this.$refs["multipleTable"].list[index].returnCode,
        },
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.detailRowData = Object.assign(
            {},
            response.rows[0],
            this.$refs["multipleTable"].list[index]
          );
          this.detailPopupsVisible = true;
          this.editPopupsState = "edit";
        }
      });
    },
  },
};
</script>
